package cn.xuewenbao.ucenter.service.impl;

import cn.xuewenbao.ucenter.entity.Member;
import cn.xuewenbao.ucenter.entity.ThirdAccount;
import cn.xuewenbao.ucenter.mapper.ThirdAccountMapper;
import cn.xuewenbao.ucenter.service.MemberService;
import cn.xuewenbao.ucenter.service.ThirdAccountService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mafayu
 * @since 2021-06-15
 */
@Service
public class ThirdAccountServiceImpl extends ServiceImpl<ThirdAccountMapper, ThirdAccount> implements ThirdAccountService {

    @Autowired
    private MemberService memberService;

    @Override
    public void updateThirdUserId(Member member, String thirdUserUuid) {
        QueryWrapper<ThirdAccount> wrapper=new QueryWrapper<>();
        wrapper.eq("third_user_uuid",thirdUserUuid);
        ThirdAccount account= baseMapper.selectOne(wrapper);

        ThirdAccount thirdAccount=new ThirdAccount();
        thirdAccount.setUserId(member.getId());
        QueryWrapper<ThirdAccount> thirdQuery=new QueryWrapper<>();
        thirdQuery.eq("user_id",thirdAccount.getUserId());
        thirdQuery.eq("third_type",account.getThirdType());
        ThirdAccount account1= baseMapper.selectOne(thirdQuery);

        if (account1!=null){
            baseMapper.deleteById(account1.getId());
        }

        baseMapper.update(thirdAccount,wrapper);
    }

    @Override
    public Member createUser(String phone, String thirdUserUuid) {
        QueryWrapper<ThirdAccount> wrapper=new QueryWrapper<>();
        wrapper.eq("third_user_uuid",thirdUserUuid);
        ThirdAccount thirdAccount= baseMapper.selectOne(wrapper);

        Member member=new Member();
        member.setMobile(phone);
        String salt = oConvertUtils.randomGen(8);
        member.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(phone, "123456", salt);
        member.setPassword(passwordEncode);
        member.setUsername(thirdAccount.getRealname());
        member.setAvatar(thirdAccount.getAvatar());
        memberService.save(member);

        thirdAccount.setUserId(member.getId());
        baseMapper.updateById(thirdAccount);

        return member;
    }

}
